<template>
    <view class="content">
        <van-popup :show="couponShow" position="bottom" round @click-overlay="closePopup"
            custom-style="width: 100%;overflow:scroll;background:#FFFFFF">
            <view class="popup-content">
                <view class="popup-title">
                    <view class="popup-title-left">优惠</view>
                    <view class="close-popup"> <van-icon name="cross" size="15" @click="closePopup" /> </view>
                </view>
                <scroll-view class="scroll-content " scroll-y :lower-threshold="120" show-scrollbar="false">
                    <view class="popup-main">
                        <view class="coupon-box" v-for="(item, index) in couponsData" :key="index" :id="'coupon-'+index">
                            <view class="coupon-box-left">
                                <!-- 无最低消费限制 -->
                                <template v-if="item.ebStoreCoupon.minPrice =='0'">
                                    <view class="coupon-box-left-top">{{!item.ebStoreCoupon.useType ? '' :(item.ebStoreCoupon.useType == 1 ? '全场通用券' :item.ebStoreCoupon.useType == 2? '商品券' : item.ebStoreCoupon.useType == 3 ?'品类券':'物业')}} {{ item.ebStoreCoupon.name }} 优惠券{{ item.ebStoreCoupon.money }}元   
                                        <span v-if="item.ebStoreCoupon.isLimited==true">(限领{{item.ebStoreCoupon.userCollectLimit}}张)</span>
                                        <span v-else>(不限量)</span></view>
                                </template>
                                <template v-else>
                                    <view class="coupon-box-left-top">{{!item.ebStoreCoupon.useType ? '' :(item.ebStoreCoupon.useType == 1 ? '全场通用券' :item.ebStoreCoupon.useType == 2? '商品券' : item.ebStoreCoupon.useType == 3 ?'品类券':'物业')}} {{ item.ebStoreCoupon.name }} 满{{item.ebStoreCoupon.minPrice}}减{{item.ebStoreCoupon.money}} 
                                        <span v-if="item.ebStoreCoupon.isLimited==true">(限领{{item.ebStoreCoupon.userCollectLimit}}张)</span>
                                        <span v-else>(不限量)</span>
                                    </view>
                                </template>
                                <template v-if="(!item.canGet && !item.isChecked) || (item.canGet && !item.isChecked)">
                                    <view class="coupon-box-left-bottom" v-if="item.ebStoreCoupon.isFixedTime|| item.ebStoreCoupon.useEndTime">{{ item.ebStoreCoupon.useEndTime }} 前可享</view>
                                    <view class="coupon-box-left-bottom" v-else-if="item.ebStoreCoupon.useStartTime && item.ebStoreCoupon.useEndTime">{{ item.ebStoreCoupon.useStartTime }}-{{ item.ebStoreCoupon.useEndTime  }} </view>
                                </template>
                                <template v-else-if="item.isChecked">
                                    <template v-if="item.userValidEbStoreCouponUserList && item.userValidEbStoreCouponUserList.length >0">
                                        <view class="coupon-box-left-bottom" v-if="item.userValidEbStoreCouponUserList[0].startTime && item.userValidEbStoreCouponUserList[0].endTime">{{ item.userValidEbStoreCouponUserList[0].deadline }} </view>
                                    </template>
                                    <template v-else>
                                        <view class="coupon-box-left-bottom" v-if="item.ebStoreCouponUserList[0].startTime && item.ebStoreCouponUserList[0].endTime">{{ item.ebStoreCouponUserList[0].deadline }} </view>
                                    </template>
                                </template>
                            </view>
                            <!-- 优惠券类型 1 手动领取, 2 新人券, 3 赠送券 -->
                            <view class="coupon-box-right" @click="toReceiveCoupon(item, 0, index)" 
                                :class="{ 'coupon-box-right-gray': item.canGet == false || item.isChecked==true }">{{ item.canGet == false  ? (item.isChecked ?'已领取':"领取" ): item.isChecked==true? '已领取':'领取' }}
                            </view>
                            <!-- <view class="coupon-box-right" @click="toJoinOrders(item, 1, index)"
                                v-if="item.minPrice !== 0">
                                {{ isJoinOrder }}
                            </view> -->

                        </view>
                        <!-- 新增：满减活动列表 -->
                         <template v-if="productType!=='services'">
                            <view class="coupon-box" v-for="(item, index) in fullDiscountData" :key="index" :id="'fullDiscount-' + index">
                                <view class="coupon-box-left">
                                    <view class="coupon-box-left-top">
                                        {{ item.name }}
                                        <span v-if="item.isLimited">(限参与{{item.limit}}次)</span>
                                    </view>
                                    <view class="coupon-box-left-bottom" v-if="item.startTime && item.endTime"> {{item.deadline}} </view>
                                </view>
            
                                <view class="coupon-box-right" @click="toJoinOrders(item, index)" v-if="productType!=='services'"> 去凑单</view>
                            </view>
                        </template>
                    </view>
                </scroll-view>
            </view>
        </van-popup>

    </view>
</template>
<script>
import {couponProductListApi,couponUserGetApi,couponUserDetailListApi,getLeFullDiscountProductListApi } from '@/api/mall'
import { formatDateSE } from '@/utils/timeUtils' // 根据实际路径引入工具函数


export default {
    props: {
        couponShow: {
            type: Boolean,
            default: () => false
        },

        pageSign: {
            type: String,
            default: () => 'find'
        },
        productId:{
            type:String,
            default: () => ''
        },
        productType:{
            type:String,
            default: () => ''
        }
    },
    data() {
        return {
            title: 'Hello',
            url: '',
            couponsData:[], // 优惠券信息
            fullDiscountData:[], // 满减活动
            useType: '',  //"使用类型 1 所有商品, 2 指定商品, 3 指定分类 ,4 物业 ")
            type: '',  //"优惠券类型 1 电商, 2 服务商品, 3 物业")

        }
    },
    watch: {
        couponShow: {
            immediate: true,
            handler(val) {
                if (val && this.pageSign !== 'find') {
                    this.getCouponUserDetailList()

                    if (this.productType!=='services') {
                        this.getLeFullDiscountProductList()
                    }
                }
            }
        },
        couponsData: {
            immediate: true, // 这句重要
            handler(val) {
                console.log('val' + val.length)

            },
            deep: true
        }
    },

    onReady() {

    },
    methods: {
        // 新增时间范围格式化方法
        formatDateRange(startTime, endTime) {
            if (!startTime || !endTime) return '有效期未知'
            let result = ''
            const now = new Date();
            const start = new Date(startTime)
            const end = new Date(endTime)
            const timeDiff = end - now;
            return `${start.getFullYear()}.${(start.getMonth() + 1).toString().padStart(2, '0')}.${start.getDate().toString().padStart(2, '0')} 至 ${end.getFullYear()}.${(end.getMonth() + 1).toString().padStart(2, '0')}.${end.getDate().toString().padStart(2, '0')}`
        },
        // 获取优惠券使用截止时间
        formatCouponEndData(endTime) {
            if (!endTime) return '有效期未知'
            const date = new Date(endTime);
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            return `${year}.${month}.${day}  ${hours}:${minutes}前可享`;
        },
        // 关闭弹窗
        closePopup() {
            this.$emit('closePopup')
        },
        // 去领取优惠券
        toReceiveCoupon(item, val, index) {
            this.currentBtn = index
            console.log(item, val, '领取优惠券')
            // if (item.canGet == false) {
            //     return false
            // }
            // if (val === 1) { // 1是去凑单
            //     uni.navigateTo({
            //         url:
            //             '/pages/shangcheng/joinOrders?params=' +
            //             encodeURIComponent(JSON.stringify(item))
            //     })
            // } else if (val === 0) { // 0是领取优惠券
                // debugger
                if (item.canGet == true) {
                    couponUserGetApi({ couponId: item.ebStoreCoupon.id }).then((res) => {
                        console.log(res, '用户领取的优惠券信息')
                        if (res.code == 200) {
                            uni.showToast({
                                icon: 'none', // 不显示图标，最多显示2行
                                title: '领取成功',
                                duration: 3000
                            })
                            // item.isChecked = false
                            this.getCouponUserDetailList()
                        }
                    })
                } else {
                    uni.showToast({
                        icon: 'none', // 不显示图标，最多显示2行
                        title: '优惠券已领完，敬请期待下次福利！',
                        duration: 3000
                    })

                    return false
                }
            // }
        },
        // 去凑单
        toJoinOrders(fullDiscountItem, index) {
            const params = {
                pageSign: 'joinOrders',
                fullDiscountItem: fullDiscountItem,
                // minPrice: item.minPrice,
                // useType: item.useType,
                // titleDate: this.formatCouponEndData(item.endTime),
            }
            // 根据满减活动参数跳转到凑单页面（示例逻辑，根据实际需求调整）
            uni.navigateTo({ url:'/pages/shangcheng/joinOrders?params='+encodeURIComponent(JSON.stringify(params)) });
        },
        // 商品对应的优惠券信息
        getCouponProductList() {
            return new Promise((resolve, reject) => {
                couponProductListApi({
                    productId: this.productId,
                }).then((res) => {
                    console.log(res, '优惠券信息')
                    if (res.code == 200) {
                        res.data.forEach(item => {
                            this.$set(item, 'isChecked', item.userGetTotal<item.userTotal && item.userGetTotal > 0)
                        })
                        this.couponsData = res.data
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },
        // // 用户领取优惠券
        // getCouponUserGet(couponId,item) {
        //     return new Promise((resolve, reject) => {
        //         couponUserGetApi({couponId:couponId}).then((res) => {
        //             console.log(res, '用户领取的优惠券信息')
        //             if (res.code == 200) {
        //                 uni.showToast({
        //                     icon: 'none', // 不显示图标，最多显示2行
        //                     title: '领取成功',
        //                     duration: 2000
        //                 })
        //                 item.canGet = false
        //                 resolve(res)
        //             }else{
        //                 reject(res)
        //             }
        //         })
        //     })
        // },
        // 用户领取的优惠券信息
        getCouponUserDetailList() {
            return new Promise((resolve, reject) => {
                couponUserDetailListApi({productId: this.productId,}).then((res) => {
                    console.log(res, '用户领取的优惠券信息')
                     if (res.code == 200) {
                        res.data.forEach(item => {
                            console.log(item.userGetTotal<item.userTotal && item.userGetTotal > 0,'7777')
                            this.$set(item, 'isChecked', item.userGetTotal<=item.userTotal && item.userGetTotal > 0)
                        })
                        this.couponsData = res.data
                        console.log(this.couponsData,'this.couponsData')
                        const now = new Date().getTime() // 获取当前时间戳
                        this.couponsData.forEach(item => {
                            if (item.userValidEbStoreCouponUserList && item.userValidEbStoreCouponUserList.length > 0) {
                                let latestEndTime;
                                const latestItem = item.userValidEbStoreCouponUserList.reduce((latest, current) => {
                                    const currentTime = new Date(current.endTime).getTime();
                                    const latestTime = latest ? new Date(latest.endTime).getTime() : 0;
                                    return currentTime > latestTime ? current : latest;
                                }, null);

                                if (latestItem) {
                                    latestEndTime = latestItem.endTime;
                                } else {
                                    // 处理列表为空的情况，这里可以设置默认值或者抛出更友好的错误
                                    latestEndTime = null; // 或者其他合适的默认值
                                }

                                item.userValidEbStoreCouponUserList.forEach(userItem => {
                                    const startTime = new Date(userItem.startTime).getTime();
                                    // Assign the latest endTime to each userItem
                                    userItem.latestEndTime = latestEndTime;
                                    // 根据当前时间与开始时间的关系设置deadline
                                    if (now > startTime) {
                                        // 当前时间超过开始时间：显示"endTime前可享"
                                        userItem.deadline = this.formatCouponEndData(latestEndTime);
                                    } else {
                                        // 当前时间未到开始时间：显示时间范围
                                        userItem.deadline = this.formatDateRange(userItem.startTime, latestEndTime);
                                    }
                                });
                            }
                            if (item.ebStoreCouponUserList && item.ebStoreCouponUserList.length > 0) {
                                let latestEndTime;
                                const latestItem = item.ebStoreCouponUserList.reduce((latest, current) => {
                                    const currentTime = new Date(current.endTime).getTime();
                                    const latestTime = latest ? new Date(latest.endTime).getTime() : 0;
                                    return currentTime > latestTime ? current : latest;
                                }, null);

                                if (latestItem) {
                                    latestEndTime = latestItem.endTime;
                                } else {
                                    // 处理列表为空的情况，这里可以设置默认值或者抛出更友好的错误
                                    latestEndTime = null; // 或者其他合适的默认值
                                }

                                item.ebStoreCouponUserList.forEach(userItem => {
                                    const startTime = new Date(userItem.startTime).getTime();
                                    // Assign the latest endTime to each userItem
                                    userItem.latestEndTime = latestEndTime;
                                    // 根据当前时间与开始时间的关系设置deadline
                                    if (now > startTime) {
                                        // 当前时间超过开始时间：显示"endTime前可享"
                                        userItem.deadline = this.formatCouponEndData(latestEndTime);
                                    } else {
                                        // 当前时间未到开始时间：显示时间范围
                                        userItem.deadline = this.formatDateRange(userItem.startTime, latestEndTime);
                                    }
                                });
                            }
                        })
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        },
        
        // 商品对应的满减活动
        getLeFullDiscountProductList() {
            return new Promise((resolve, reject) => {
                getLeFullDiscountProductListApi({
                    productId: this.productId,
                }).then((res) => {
                    console.log(res, '满减活动')
                    if (res.code == 200) {
                        this.fullDiscountData = res.data
                        const now = new Date().getTime() // 获取当前时间戳
                        this.fullDiscountData.forEach(item => {
                            const startTime = new Date(item.startTime).getTime()
                            // 根据当前时间与开始时间的关系设置deadline
                            if (now > startTime) {
                                // 当前时间超过开始时间：显示"endTime前可享"
                                item.deadline = this.formatCouponEndData(item.endTime)
                            } else {
                                // 当前时间未到开始时间：显示时间范围
                                item.deadline = this.formatDateRange(item.startTime, item.endTime)
                            }
                        })
                        console.log(this.fullDiscountData,'满减活动')
                        resolve(res)
                    } else {
                        reject(res)
                    }
                })
            })
        }

    }
}
</script>
<style lang="scss" scoped>

// 最外层
.content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    overflow-y: auto;
    z-index: -2;
    scrollbar-width: none;
    /* 针对Firefox */
}

// 滚动
.scroll-content {
    flex: 1;
    height: 1px;
}

// 提示框
// .popup-content {

//     padding: 24px;
//     border-radius: 16px;
//     overflow: hidden;
//     // height:100vh;
//     height: 100%;

//     .popup-main {
//         display: flex;
//         flex-direction: column;
//         box-sizing: border-box;
//         height: calc(100% - 30px);
//     }

// }

// 弹窗
.popup-content {
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    background: #FFFFFF;
    overflow: hidden;
    // box-shadow: 0px 8px 20px rgba(61, 92, 153, 0.1);
    border-radius: 12px;
    padding: 24px;
    height: 100%;

    .popup-title {
        display: flex;
        justify-content: space-between;
        font-style: normal;
        line-height:40rpx;
        // font-weight: bold;
        font-size: 40rpx;
        text-align: left;
        color: #111111;
    }

    .popup-main {
        margin-top: 46px;
        width: 100%;
    }

    .coupon-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 44px;

        .coupon-box-left {

            .coupon-box-left-top {
                // font-weight: bold;
                font-size: 28rpx;
                text-align: left;
                color: #111111;
                // line-height: 28rpx;
            }

            .coupon-box-left-bottom {
                // font-weight: 400;
                font-size: 24rpx;
                text-align: left;
                color: #666666;
                line-height: 24rpx;
                margin-top: 13px;
            }
        }

        .coupon-box-right {
            min-width: 116rpx;
            text-align: center;
            color: #111111;
            font-size: 24rpx;
            border-radius: 20rpx;
            border: 1px solid #333333;
            height: 40rpx;
            line-height: 40rpx;
        }
        .coupon-box-right-gray{
            min-width: 116rpx;
            text-align: center;
            color: #888888;
            font-size: 24rpx;
            border-radius: 20rpx;
            border: 1px solid #888888;
            height: 40rpx;
            line-height: 40rpx;
        }

    }

    // .coupon-box:last-child{
    //     margin-bottom: 0px;
    // }

    .close-popup {
        height: 12px;
        // margin-top: 24px;
        text-align: center;
    }
}
</style>
